<template>
  <el-form
    ref="deptForm"
    :model="form"
    :rules="rules"
    label-width="120px"
  >
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <el-option
          v-for="item in list"
          :key="item.id"
          :value="item.username"
          :label="item.username"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="hCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getEmployeesSimple, addDepartments, getDepartmentsDetail, editDepartments } from '@/api/departments'
export default {
  props: {
    isEdit: {
      type: Boolean,
      required: true
    },
    id: {
      type: String,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    const existCodeValid = (rule, value, callback) => {
      // console.log(rule, 'rule')// 校验规则的数据类型等等
      // console.log(value, 'value')// 当前的值
      // console.log(callback, 'callback')// 这个表单数据的判断处理正确与错误的回调

      /* code的去重校验规则：
            1.找到所有的code组成一个列表(所有的) */
      let existCodeList = this.originList.map(item => {
        return item.code
      })
      // 2.找到除了自身外的列表
      existCodeList = this.originList.filter(item => item.id !== this.id).map(item => item.code)
      if (existCodeList.includes(value)) {
        callback(new Error(`部门编码：${value}已存在`))
        console.log(existCodeList, 'existCodeList')
      } else {
        callback()
      }
    }
    const existnameValid = (rule, value, callback) => {
      // 验证输入部门名称value在同级不能重复
      let existNameList = this.originList.filter(item => item.pid === this.id).map(item => item.name)
      console.log(existNameList, 'existNameList')// 过滤出来了有子集的每一项的name
      if (this.isEdit) {
        const pid = existNameList.filter(item => item.id === this.id).pid// 自己的pid
        const brothers = existNameList.filter(item => item.pid).map(item => item.pid)// 全部的pid
        existNameList = brothers.filter(item => item.pid === pid).map(item => item.name)// 把自己过滤掉剩下存在的
      }
      if (existNameList.includes(value)) {
        callback(new Error(`部门编码：${value}已存在`))
      } else {
        callback()
      }
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      list: [], // 部门负责人
      rules: {
        name: [
          { required: true, message: '请输入部门的名称', trigger: 'blur' },
          { min: 1, max: 30, message: '请输入1-30位', trigger: 'blur' },
          { validator: existnameValid, trigger: 'blur' }

        ],
        code: [
          { required: true, message: '请输入部门的编号', trigger: 'blur' },
          { min: 1, max: 30, message: '请输入1-30位', trigger: 'blur' },
          { validator: existCodeValid, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请选择部门负责人', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入部门的编号', trigger: 'blur' },
          { min: 1, max: 200, message: '请输入部门的介绍', trigger: 'blur' }
        ]
      }
    }
    // 自定义校验规则，注意位置是在data中，return外面
    // con's't
  },
  created() {
    this.loadEmployeesSimple()
    if (this.isEdit) { this.loadDeparamentDetail() }
  },
  methods: {
    // 1.确认与取消按钮模块
    hSubmit() {
      // 开始兜底校验
      this.$refs.deptForm.validate((valId) => {
        if (!valId) return
        this.isEdit ? this.doEdit() : this.doAdd()// 根据我们从父组件传递过来的isEdit做判断，true走编辑接口，false则走新增接口
      })
    },
    hCancel() {
      // 关闭弹窗，弹窗在父组件
      this.$emit('doClose')
    },
    // 2.部门模块
    // 2.1部门负责人信息获取
    async loadEmployeesSimple() {
      const res = await getEmployeesSimple()
      this.list = res.data
      console.log(res, '部门负责人信息')
    },
    // 2.2新增部门模块
    async doAdd() {
      try {
        const res = await addDepartments({ ...this.form, pid: this.id })
        console.log(res, 'doAdd')
        // 子传父用来关闭弹窗与刷新
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 2.3部门详情模块
    async loadDeparamentDetail() {
      try {
        const res = await getDepartmentsDetail(this.id)
        console.log(res, '部门信息详情')
        this.form = res.data// 将数据反馈给我们的表单
      } catch (error) {
        console.log(error)
      }
    },
    // 2.4编辑部门
    async doEdit() {
      try {
        const res = await editDepartments(this.form)
        console.log(res, '编辑部门')
        // 子传父用来关闭弹窗与刷新
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 清空表单
    resetForm() {
      this.$refs.deptForm.resetFields()
    }
  }
}
</script>

<style>

</style>
